<template>
  <div
    v-if="visible || isCommentMode"
    class="text-selection-toolbar"
    :class="{ 'comment-mode-active': isCommentMode }"
    :style="toolbarStyle"
    @click.stop="handleToolbarClick"
    @mousedown.stop="handleToolbarMouseDown"
  >
    <!-- 批注模式 -->
    <div v-if="isCommentMode" class="comment-mode" @click.stop @mousedown.stop @mouseup.stop>
      <!-- 批注输入框 -->
      <div class="comment-input-wrapper" @click.stop @mousedown.stop @mouseup.stop>
        <textarea
          ref="commentInput"
          v-model="commentText"
          class="comment-input"
          placeholder="请输入批注内容..."
          @input.stop
          @keydown.stop
          @keyup.stop
          @keypress.stop
          @focus.stop
          @blur.stop
        ></textarea>
      </div>

      <!-- 批注操作按钮 -->
      <div class="comment-actions">
        <button
          class="toolbar-btn comment-btn submit-btn"
          @click.stop="handleSubmitComment"
          title="提交批注"
        >
          <i class="sjqeditor queding"></i>
          <span>确定</span>
        </button>

        <button
          class="toolbar-btn comment-btn cancel-btn"
          @click.stop="handleCancelComment"
          title="取消批注"
        >
          <i class="sjqeditor quxiao"></i>
          <span>取消</span>
        </button>
      </div>
    </div>

    <!-- 正常模式 -->
    <div v-else class="normal-mode">
      <!-- 改写按钮 -->
      <button
        class="toolbar-btn"
        @click.stop="handleRewrite"
        title="改写"
        :disabled="loading"
      >
        <i v-if="!loading" class="sjqeditor gaixie"></i>
        <i v-else class="el-icon-loading"></i>
        <span>改写</span>
      </button>

      <!-- 续写按钮 -->
      <button
        class="toolbar-btn"
        @click.stop="handleContinue"
        title="续写"
        :disabled="loading"
      >
        <i v-if="!loading" class="sjqeditor xuxie"></i>
        <i v-else class="el-icon-loading"></i>
        <span>续写</span>
      </button>

      <!-- 缩写按钮 -->
      <button
        class="toolbar-btn"
        @click.stop="handleAbbreviate"
        title="缩写"
        :disabled="loading"
      >
        <i class="sjqeditor suoxie"></i>
        <span>缩写</span>
      </button>

      <!-- 分隔线 -->
      <div class="separator"></div>

      <!-- 翻译按钮 -->
      <button
        class="toolbar-btn"
        @click.stop="handleTranslate"
        title="翻译"
        :disabled="loading"
      >
        <i class="sjqeditor fanyi-19"></i>
        <span>翻译</span>
      </button>

      <!-- 分隔线 -->
      <div class="separator"></div>


      <!-- 智能纠错按钮 -->
      <button
        class="toolbar-btn"
        @click.stop="handleSpellCheck"
        title="智能纠错"
        :disabled="loading"
      >
        <i class="sjqeditor cuobiezijiance-24"></i>
        <span>智能纠错</span>
      </button>

      <!-- 错别字检测按钮 -->
      <!-- <button
        class="toolbar-btn"
        @click.stop="handleSpellCheck"
        title="错别字检测"
        :disabled="loading"
      >
        <i class="sjqeditor cuobiezijiance-24"></i>
        <span>错别字检测</span>
      </button> -->

      <!-- 敏感词检测按钮 -->
      <!-- <button
        class="toolbar-btn"
        @click.stop="handleSensitiveCheck"
        title="敏感词检测"
        :disabled="loading"
      >
        <i class="sjqeditor mingancijiance"></i>
        <span>敏感词检测</span>
      </button> -->

      <!-- 拼写语法检测按钮 -->
      <!-- <button
        class="toolbar-btn"
        @click.stop="handleGrammarCheck"
        title="拼写语法检测"
        :disabled="loading"
      >
        <i class="sjqeditor pinxieyufajiance"></i>
        <span>拼写语法检测</span>
      </button> -->

      <!-- 批注按钮 -->
      <button
        class="toolbar-btn"
        @click.stop="handleComment"
        title="批注"
        :disabled="loading"
      >
        <i class="sjqeditor pizhu"></i>
        <span>批注</span>
      </button>
    </div>

    <!-- 加载遮罩层 -->
    <transition name="loading-fade">
      <div v-if="loading" class="loading-overlay" @click.stop @mousedown.stop @mouseup.stop>
        <div class="loading-spinner">
          <i class="el-icon-loading"></i>
          <div class="loading-dots">
            <span class="dot"></span>
            <span class="dot"></span>
            <span class="dot"></span>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { textProcessingAPI } from './api/textProcessingAPI'

export default {
  name: 'TextSelectionToolbar',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    selectedText: {
      type: String,
      default: ''
    },
    position: {
      type: Object,
      default: () => ({ x: 0, y: 0 })
    },
    triggerComment: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isCommentMode: false,
      commentText: '',
      loading: false
    }
  },
  computed: {
    toolbarStyle() {
      const style = {
        left: `${this.position.x}px`,
        top: `${this.position.y}px`
      }
      return style
    }
  },

  watch: {
    visible(newVal) {
      // 当工具栏隐藏时，退出批注模式
      if (!newVal && !this.isCommentMode) {
        this.exitCommentMode()
      }
    },
    isCommentMode(newVal) {
      if (newVal) {
        // 进入批注模式时，聚焦到输入框
        this.$nextTick(() => {
          if (this.$refs.commentInput) {
            this.$refs.commentInput.focus()
          }
        })
      }
    },
    triggerComment(newVal) {
      // 当触发批注标志为true时，进入批注模式
      if (newVal && this.visible) {
        this.enterCommentMode()
      }
    }
  },

  mounted() {
    // 监听父组件发送的text-comment事件
    // 在Vue 3中，我们通过watch来监听父组件的数据变化
  },

  beforeDestroy() {
    // 移除事件监听
  },
  methods: {
    // 改写功能
    async handleRewrite() {
      if (!this.selectedText.trim()) {
        this.$message.warning('请先选择要改写的文本')
        return
      }

      this.loading = true
      try {
        const response = await textProcessingAPI.rewrite(this.selectedText)
        console.log('改写API响应:', response)
        
        // 发送改写结果到父组件
        this.$emit('rewrite', {
          originalText: this.selectedText,
          result: response
        })
      } catch (error) {
        console.error('改写功能调用失败:', error)
        this.$message.error('改写功能调用失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    // 续写功能
    async handleContinue() {
      if (!this.selectedText.trim()) {
        this.$message.warning('请先选择要续写的文本')
        return
      }

      this.loading = true
      try {
        const response = await textProcessingAPI.continueWriting(this.selectedText)
        console.log('续写API响应:', response)
        
        // 发送续写结果到父组件
        this.$emit('continue', {
          originalText: this.selectedText,
          result: response
        })
      } catch (error) {
        console.error('续写功能调用失败:', error)
        this.$message.error('续写功能调用失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    // 缩写功能
    async handleAbbreviate() {
      if (!this.selectedText.trim()) {
        this.$message.warning('请先选择要缩写的文本')
        return
      }
      this.loading = true
      try {
        const response = await textProcessingAPI.abbreviate(this.selectedText)
        console.log('缩写API响应:', response)
        this.$emit('abbreviate', {
          originalText: this.selectedText,
          result: response
        })
      } catch (error) {
        console.error('缩写功能调用失败:', error)
        this.$message.error('缩写功能调用失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    // 翻译功能
    async handleTranslate() {
      if (!this.selectedText.trim()) {
        this.$message.warning('请先选择要翻译的文本')
        return
      }
      this.loading = true
      try {
        const response = await textProcessingAPI.translate(this.selectedText)
        console.log('翻译API响应:', response)
        this.$emit('translate', {
          originalText: this.selectedText,
          result: response
        })
      } catch (error) {
        console.error('翻译功能调用失败:', error)
        this.$message.error('翻译功能调用失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    // 智能纠错功能
    async handleSpellCheck() {
      if (!this.selectedText.trim()) {
        this.$message.warning('请先选择要纠错的文本')
        return
      }
      this.loading = true
      try {
        const response = await textProcessingAPI.smartCorrection(this.selectedText)
        console.log('智能纠错API响应:', response)
        this.$emit('spell-check', {
          originalText: this.selectedText,
          result: response
        })
      } catch (error) {
        console.error('智能纠错功能调用失败:', error)
        this.$message.error('智能纠错功能调用失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    // 敏感词检测功能
    // handleSensitiveCheck() {
    //   this.$emit('sensitive-check', this.selectedText)
    // },

    // 拼写语法检测功能
    // handleGrammarCheck() {
    //   this.$emit('grammar-check', this.selectedText)
    // },

    // 批注功能 - 进入批注模式
    handleComment() {
      // 触发批注事件，让父组件高亮文本
      this.$emit('comment', { action: 'highlight' })
      this.enterCommentMode()
    },

    // 进入批注模式
    enterCommentMode() {
      this.isCommentMode = true
      this.commentText = ''
      // 确保工具栏在批注模式下保持可见
      this.$emit('comment-mode-enter')
    },

    // 退出批注模式
    exitCommentMode(data) {
      this.isCommentMode = false
      this.commentText = ''
      // 通知父组件退出批注模式
      this.$emit('comment-mode-exit',data)
    },

    // 提交批注
    handleSubmitComment() {
      if (this.commentText.trim()) {
        // 创建批注对象
        const comment = {
          id: Date.now().toString(), // 使用时间戳作为唯一ID
          selectedText: this.selectedText,
          content: this.commentText.trim(),
          timestamp: new Date().toISOString()
        }

        // 发送批注数据到父组件
        this.$emit('submit-comment', comment)
        this.exitCommentMode('确定')
      }
    },

    // 取消批注
    handleCancelComment() {
      this.exitCommentMode()
    },

    // 工具栏点击事件
    handleToolbarClick(event) {
      event.preventDefault()
    },

    // 工具栏鼠标按下事件
    handleToolbarMouseDown(event) {
      event.preventDefault()
    },

    // 处理父组件发送的批注事件
    handleParentComment(data) {
      if (data && data.action === 'highlight') {
        // 进入批注模式
        this.enterCommentMode()
      }
    },


  }
}
</script>

<style scoped>
@import './font/iconfont.css';
.text-selection-toolbar {
  position: fixed;
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
  z-index: 99999;
  font-size: 12px;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  pointer-events: auto;
}

/* 批注模式下保持工具栏可见 */
.text-selection-toolbar.comment-mode-active {
  display: flex !important;
  visibility: visible !important;
  opacity: 1 !important;
}

/* 批注模式样式 */
.comment-mode {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 300px;
}

.comment-input-wrapper {
  width: 100%;
}

.comment-input {
  width: 100%;
  min-height: 80px;
  padding: 8px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 12px;
  font-family: inherit;
  resize: vertical;
  outline: none;
  transition: border-color 0.2s ease;
}

.comment-input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.comment-actions {
  display: flex;
  gap: 4px;
  justify-content: flex-end;
}

.comment-btn {
  min-width: 60px;
  padding: 6px 12px;
}

.submit-btn {
  background: #3b82f6;
  color: white;
}

.submit-btn:hover {
  background: #2563eb;
  color: white;
}

.cancel-btn {
  background: #6b7280;
  color: white;
}

.cancel-btn:hover {
  background: #4b5563;
  color: white;
}

/* 正常模式样式 */
.normal-mode {
  display: flex;
  align-items: center;
  gap: 4px;
}

.toolbar-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 6px 8px;
  border: none;
  background: transparent;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 50px;
  color: #374151;
  font-size: .7vw;
  line-height: 1.2;
}

.toolbar-btn:hover {
  background: #E6F3FF;
  color: #111827;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-btn:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.toolbar-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.toolbar-btn:disabled:hover {
  background: transparent;
  color: #374151;
  transform: none;
  box-shadow: none;
}

.el-icon-loading {
  animation: spin 1s linear infinite;
}

.toolbar-btn i {
  font-size: 16px;
  margin-bottom: 2px;
  color: #6b7280;
}

.toolbar-btn:hover i {
  color: #374151;
}

.toolbar-btn span {
  font-size: .6vw;
  white-space: nowrap;
}

.separator {
  width: 1px;
  height: 32px;
  background: #d1d5db;
  margin: 0 2px;
}

/* 加载遮罩层样式 */
.loading-overlay {
  position: absolute;
  top: -8px;
  left: -8px;
  right: -8px;
  bottom: -8px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(2px);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  z-index: 10;
  animation: pulse 2s ease-in-out infinite;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #6b7280;
}

.loading-spinner i {
  font-size: 20px;
  color: #3b82f6;
  animation: spin 1s linear infinite;
}

.loading-dots {
  display: flex;
  gap: 4px;
  align-items: center;
}

.dot {
  width: 6px;
  height: 6px;
  background: #3b82f6;
  border-radius: 50%;
  animation: dotPulse 1.4s ease-in-out infinite both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

.dot:nth-child(3) {
  animation-delay: 0s;
}

@keyframes dotPulse {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 脉冲动画 */
@keyframes pulse {
  0%, 100% {
    opacity: 0.9;
    transform: scale(1);
  }
  50% {
    opacity: 0.95;
    transform: scale(1.02);
  }
}

/* 旋转动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}





/* 遮罩层动画 */
.loading-fade-enter-active,
.loading-fade-leave-active {
  transition: all 0.3s ease;
}

.loading-fade-enter-from {
  opacity: 0;
  transform: scale(0.95);
}

.loading-fade-leave-to {
  opacity: 0;
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .text-selection-toolbar {
    flex-wrap: wrap;
    max-width: 300px;
    gap: 2px;
  }

  .comment-mode {
    min-width: 250px;
  }

  .toolbar-btn {
    min-width: 40px;
    padding: 4px 6px;
  }

  .toolbar-btn span {
    font-size: 9px;
  }
}
</style>
